package com.example.springdemo.domain.practice;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;


//@Component
public class CustomValueBeanPostProcessor implements EnvironmentAware, BeanPostProcessor {
    private Environment env; // 改为非 static

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment; // 直接赋值给成员变量
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(CustomValue.class)) {
                declaredField.setAccessible(true);
                CustomValue annotation = declaredField.getAnnotation(CustomValue.class);
                String annotationValue = annotation.value();
                if (StringUtils.isEmpty(annotationValue)) {
                    throw new RuntimeException("value 不可以为空");
                }

                // 获取属性值
                String propertyValue = env.getProperty(annotationValue);
                if (propertyValue == null) {
                    throw new RuntimeException("Property '" + annotationValue + "' not found in Environment");
                }

                // 类型转换（示例：支持 String -> int）
                Object value = propertyValue;
                if (declaredField.getType() == int.class || declaredField.getType() == Integer.class) {
                    value = Integer.parseInt(propertyValue);
                } // 可扩展其他类型

                // 设置字段值
                try {
                    declaredField.set(bean, value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Failed to set field '" + declaredField.getName() + "'", e);
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}